package com.cmdi.mq.log.aspect;

import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.URLUtil;
import com.cmdi.mq.domain.SysUserLog;
import com.cmdi.mq.log.annotation.SysLog;
import com.cmdi.mq.log.event.LogEvent;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.core.LocalVariableTableParameterNameDiscoverer;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpHeaders;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

/**
 * @Description: WebLogAspect切面
 * @Author: gaozb
 */
@Component
@Aspect
@Order(1)
@Slf4j
public class WebLogAspect {
    @Autowired
    private ApplicationEventPublisher applicationEventPublisher;

    @Pointcut("@annotation(com.cmdi.mq.log.annotation.SysLog)")
    public void webLog(){}

    @Around("webLog()")
    public Object recordLog(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        //WebLog webLog = new WebLog();
        SysUserLog sysUserLog = new SysUserLog();
        long start = System.currentTimeMillis() ;
        // 执行方法的真实调用
        Object result = proceedingJoinPoint.proceed(proceedingJoinPoint.getArgs());
        long end = System.currentTimeMillis() ;
        // 请求该接口花费的时间
        sysUserLog.setSpendtime((long) (end - start) / 1000);
        // 获取当前请求的request对象
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        // 设置请求的uri路径等
        String url = request.getRequestURL().toString();
        sysUserLog.setUri(request.getRequestURI());
        sysUserLog.setUrl(url);
        sysUserLog.setBasepath(StrUtil.removeSuffix(url, URLUtil.url(url).getPath()));
        // 获取安全的上下文
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        //System.out.println(authentication);
        //设置当前登录用户，如果不需要用户授权即可访问那么设置为匿名anonymous
//        System.out.println(authentication.getPrincipal());
        sysUserLog.setUsername(authentication== null ? "anonymous":authentication.getPrincipal().toString());
        // 获取ip地址
        sysUserLog.setIp(request.getRemoteAddr());

        // 获取方法
        MethodSignature signature = (MethodSignature)proceedingJoinPoint.getSignature();
        // 获取类的名称
        String targetClassName = proceedingJoinPoint.getTarget().getClass().getName();
        Method method = signature.getMethod();
        // 因为我们会使用Swagger 这工具，我们必须在方法上面添加@ApiOperation(value="")该注解，获取ApiOperation
        // ApiOperation annotation = method.getAnnotation(ApiOperation.class);
        // 因为我们会使用@SysLog注解，直接获取注解的value值
        SysLog annotation = method.getAnnotation(SysLog.class);
        //设置描述、方法名、参数值
        sysUserLog.setDescription(annotation == null ? "nodesc":annotation.value());
        sysUserLog.setMethod(targetClassName+"."+method.getName());
        //webLog.setParameter(getMethodParameter(method,proceedingJoinPoint.getArgs()));
        sysUserLog.setParameter(getMethodParameter2(proceedingJoinPoint).toString());
        //设置返回值，返回值比较大，一般无需设置
        //webLog.setResult(result);
        //处理
        //log.info(JSON.toJSONString(webLog,true));
        applicationEventPublisher.publishEvent(new LogEvent(sysUserLog, request.getHeader(HttpHeaders.AUTHORIZATION)));
        return result;
    }

    /**
     * 获取方法的执行参数
     * @param method
     * @param args
     * @return
     * {"key_参数的名称":"value_参数的值"}
     */
    private Object getMethodParameter(Method method, Object[] args) {
        Map<String, Object> methodParametersWithValues = new HashMap<>();
        LocalVariableTableParameterNameDiscoverer localVariableTableParameterNameDiscoverer =
                new LocalVariableTableParameterNameDiscoverer();
        // 方法的形参名称
        String[] parameterNames = localVariableTableParameterNameDiscoverer.getParameterNames(method);
        for (int i = 0; i <parameterNames.length ; i++) {
            System.out.println(parameterNames[i]);
            if(parameterNames[i].equals("password") || parameterNames[i].equals("file")) {
                methodParametersWithValues.put(parameterNames[i],"受限的支持类型") ;
            }else{
                methodParametersWithValues.put(parameterNames[i],args[i]) ;
            }

        }
        return methodParametersWithValues ;
    }

    /**
     * 获取方法的执行参数
     * @param joinPoint
     * @return
     * {"key_参数的名称":"value_参数的值"}
     */
    private Object getMethodParameter2(ProceedingJoinPoint joinPoint) {
        Map<String, Object> methodParametersWithValues = new HashMap<>();
        String[] parameterNames = ((MethodSignature) joinPoint.getSignature()).getParameterNames();
        Object[] args = joinPoint.getArgs();
//        System.out.println(args.length == parameterNames.length);
        // 方法的形参名称
        for (int i = 0; i < parameterNames.length ; i++) {
//            System.out.println(parameterNames[i] + ":" + args[i]);
            if(parameterNames[i].equals("password") || parameterNames[i].equals("file")) {
                methodParametersWithValues.put(parameterNames[i],"受限") ;
            } else if(args[i] instanceof ServletRequest || args[i] instanceof ServletResponse || args[i] instanceof HttpSession || args[i] instanceof MultipartFile) {
                continue;
            }else{
                methodParametersWithValues.put(parameterNames[i],args[i]) ;
            }

        }
        return methodParametersWithValues ;
    }

}